home *** CD-ROM | disk | FTP | other *** search
/ BCI NET 2 / BCI NET 2.iso / archives / programming / source / a2.0bemacs-src.lha / Emacs-19.25 / src / callproc.c! < prev    next >
Encoding:
Text File  |  1994-08-29  |  27.7 KB  |  1,032 lines

  1. /* Synchronous subprocess invocation for GNU Emacs.
  2.    Copyright (C) 1985, 1986, 1987, 1988, 1993, 1994 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20.  
  21. #include <signal.h>
  22. #include <errno.h>
  23. #include <stdio.h>
  24.  
  25. #include <config.h>
  26.  
  27. #include "paths.h"
  28.  
  29. extern int errno;
  30. extern char *strerror ();
  31.  
  32. /* Define SIGCHLD as an alias for SIGCLD.  */
  33.  
  34. #if !defined (SIGCHLD) && defined (SIGCLD)
  35. #define SIGCHLD SIGCLD
  36. #endif /* SIGCLD */
  37.  
  38. #include <sys/types.h>
  39.  
  40. #include <sys/file.h>
  41. #ifdef USG5
  42. #define INCLUDED_FCNTL
  43. #include <fcntl.h>
  44. #endif
  45.  
  46. #ifdef MSDOS    /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
  47. #define INCLUDED_FCNTL
  48. #include <fcntl.h>
  49. #include <sys/stat.h>
  50. #include <sys/param.h>
  51. #include <errno.h>
  52. #endif /* MSDOS */
  53.  
  54. #ifndef O_RDONLY
  55. #define O_RDONLY 0
  56. #endif
  57.  
  58. #ifndef O_WRONLY
  59. #define O_WRONLY 1
  60. #endif
  61.  
  62. #include "lisp.h"
  63. #include "commands.h"
  64. #include "buffer.h"
  65. #include <paths.h>
  66. #include "process.h"
  67. #include "syssignal.h"
  68. #include "systty.h"
  69.  
  70. #ifdef VMS
  71. extern noshare char **environ;
  72. #else
  73. extern char **environ;
  74. #endif
  75.  
  76. #define max(a, b) ((a) > (b) ? (a) : (b))
  77.  
  78. #ifdef MSDOS
  79. /* When we are starting external processes we need to know whether they
  80.    take binary input (no conversion) or text input (\n is converted to
  81.    \r\n).  Similar for output: if newlines are written as \r\n then it's
  82.    text process output, otherwise it's binary.  */
  83. Lisp_Object Vbinary_process_input;
  84. Lisp_Object Vbinary_process_output;
  85. #endif
  86.  
  87. Lisp_Object Vexec_path, Vexec_directory, Vdata_directory, Vdoc_directory;
  88. Lisp_Object Vconfigure_info_directory;
  89.  
  90. Lisp_Object Vshell_file_name;
  91.  
  92. Lisp_Object Vprocess_environment;
  93.  
  94. #ifdef MSDOS
  95. Lisp_Object Qbuffer_file_type;
  96. #endif
  97.  
  98. /* True iff we are about to fork off a synchronous process or if we
  99.    are waiting for it.  */
  100. int synch_process_alive;
  101.  
  102. /* Nonzero => this is a string explaining death of synchronous subprocess.  */
  103. char *synch_process_death;
  104.  
  105. /* If synch_process_death is zero,
  106.    this is exit code of synchronous subprocess.  */
  107. int synch_process_retcode;
  108.  
  109. extern Lisp_Object Vdoc_file_name;
  110.  
  111. /* Clean up when exiting Fcall_process.
  112.    On MSDOS, delete the temporary file on any kind of termination.
  113.    On Unix, kill the process and any children on termination by signal.  */
  114.  
  115. /* Nonzero if this is termination due to exit.  */
  116. static int call_process_exited;
  117.  
  118. #ifndef VMS  /* VMS version is in vmsproc.c.  */
  119.  
  120. static Lisp_Object
  121. call_process_kill (fdpid)
  122.      Lisp_Object fdpid;
  123. {
  124.   close (XFASTINT (Fcar (fdpid)));
  125.   EMACS_KILLPG (XFASTINT (Fcdr (fdpid)), SIGKILL);
  126.   synch_process_alive = 0;
  127.   return Qnil;
  128. }
  129.  
  130. Lisp_Object
  131. call_process_cleanup (fdpid)
  132.      Lisp_Object fdpid;
  133. {
  134. #ifdef MSDOS
  135.   /* for MSDOS fdpid is really (fd . tempfile)  */
  136.   register Lisp_Object file;
  137.   file = Fcdr (fdpid);
  138.   close (XFASTINT (Fcar (fdpid)));
  139.   if (strcmp (XSTRING (file)-> data, NULL_DEVICE) != 0)
  140.     unlink (XSTRING (file)->data);
  141. #else /* not MSDOS */
  142.   register int pid = XFASTINT (Fcdr (fdpid));
  143.  
  144.  
  145.   if (call_process_exited)
  146.     {
  147.       close (XFASTINT (Fcar (fdpid)));
  148.       return Qnil;
  149.     }
  150.  
  151.   if (EMACS_KILLPG (pid, SIGINT) == 0)
  152.     {
  153.       int count = specpdl_ptr - specpdl;
  154.       record_unwind_protect (call_process_kill, fdpid);
  155.       message1 ("Waiting for process to die...(type C-g again to kill it instantly)");
  156.       immediate_quit = 1;
  157.       QUIT;
  158.       wait_for_termination (pid);
  159.       immediate_quit = 0;
  160.       specpdl_ptr = specpdl + count; /* Discard the unwind protect.  */
  161.       message1 ("Waiting for process to die...done");
  162.     }
  163.   synch_process_alive = 0;
  164.   close (XFASTINT (Fcar (fdpid)));
  165. #endif /* not MSDOS */
  166.   return Qnil;
  167. }
  168.  
  169. DEFUN ("call-process", Fcall_process, Scall_process, 1, MANY, 0,
  170.   "Call PROGRAM synchronously in separate process.\n\
  171. The program's input comes from file INFILE (nil means `/dev/null').\n\
  172. Insert output in BUFFER before point; t means current buffer;\n\
  173.  nil for BUFFER means discard it; 0 means discard and don't wait.\n\
  174. Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
  175. Remaining arguments are strings passed as command arguments to PROGRAM.\n\
  176. If BUFFER is 0, returns immediately with value nil.\n\
  177. Otherwise waits for PROGRAM to terminate\n\
  178. and returns a numeric exit status or a signal description string.\n\
  179. If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
  180.   (nargs, args)
  181.      int nargs;
  182.      register Lisp_Object *args;
  183. {
  184.   Lisp_Object infile, buffer, current_dir, display, path;
  185.   int fd[2];
  186.   int filefd;
  187.   register int pid;
  188.   char buf[1024];
  189.   int count = specpdl_ptr - specpdl;
  190.   register unsigned char **new_argv
  191.     = (unsigned char **) alloca ((max (2, nargs - 2)) * sizeof (char *));
  192.   struct buffer *old = current_buffer;
  193. #ifdef MSDOS    /* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
  194.   char *outf, *tempfile;
  195.   int outfilefd;
  196. #endif
  197. #if 0
  198.   int mask;
  199. #endif
  200.   CHECK_STRING (args[0], 0);
  201.  
  202. #ifndef subprocesses
  203.   /* Without asynchronous processes we cannot have BUFFER == 0.  */
  204.   if (nargs >= 3 && XTYPE (args[2]) == Lisp_Int)
  205.     error ("Operating system cannot handle asynchronous subprocesses");
  206. #endif /* subprocesses */
  207.  
  208.   if (nargs >= 2 && ! NILP (args[1]))
  209.     {
  210.       infile = Fexpand_file_name (args[1], current_buffer->directory);
  211.       CHECK_STRING (infile, 1);
  212.     }
  213.   else
  214.     infile = build_string (NULL_DEVICE);
  215.  
  216.   if (nargs >= 3)
  217.     {
  218.       register Lisp_Object tem;
  219.  
  220.       buffer = tem = args[2];
  221.       if (!(EQ (tem, Qnil)
  222.         || EQ (tem, Qt)
  223.         || XFASTINT (tem) == 0))
  224.     {
  225.       buffer = Fget_buffer (tem);
  226.       CHECK_BUFFER (buffer, 2);
  227.     }
  228.     }
  229.   else 
  230.     buffer = Qnil;
  231.  
  232.   /* Make sure that the child will be able to chdir to the current
  233.      buffer's current directory, or its unhandled equivalent.  We
  234.      can't just have the child check for an error when it does the
  235.      chdir, since it's in a vfork.
  236.  
  237.      We have to GCPRO around this because Fexpand_file_name,
  238.      Funhandled_file_name_directory, and Ffile_accessible_directory_p
  239.      might call a file name handling function.  The argument list is
  240.      protected by the caller, so all we really have to worry about is
  241.      buffer.  */
  242.   {
  243.     struct gcpro gcpro1, gcpro2, gcpro3;
  244.  
  245.     current_dir = current_buffer->directory;
  246.  
  247.     GCPRO3 (infile, buffer, current_dir);
  248.  
  249.     current_dir
  250.       = expand_and_dir_to_file (Funhandled_file_name_directory (current_dir),
  251.                 Qnil);
  252.     if (NILP (Ffile_accessible_directory_p (current_dir)))
  253.       report_file_error ("Setting current directory",
  254.              Fcons (current_buffer->directory, Qnil));
  255.  
  256.     UNGCPRO;
  257.   }
  258.  
  259.   display = nargs >= 4 ? args[3] : Qnil;
  260.  
  261.   filefd = open (XSTRING (infile)->data, O_RDONLY, 0);
  262.   if (filefd < 0)
  263.     {
  264.       report_file_error ("Opening process input file", Fcons (infile, Qnil));
  265.     }
  266.   /* Search for program; barf if not found.  */
  267.   {
  268.     struct gcpro gcpro1;
  269.  
  270.     GCPRO1 (current_dir);
  271.     openp (Vexec_path, args[0], EXEC_SUFFIXES, &path, 1);
  272.     UNGCPRO;
  273.   }
  274.   if (NILP (path))
  275.     {
  276.       close (filefd);
  277.       report_file_error ("Searching for program", Fcons (args[0], Qnil));
  278.     }
  279.   new_argv[0] = XSTRING (path)->data;
  280.   {
  281.     register int i;
  282.     for (i = 4; i < nargs; i++)
  283.       {
  284.     CHECK_STRING (args[i], i);
  285.     new_argv[i - 3] = XSTRING (args[i])->data;
  286.       }
  287.     new_argv[i - 3] = 0;
  288.   }
  289.  
  290. #ifdef MSDOS /* MW, July 1993 */
  291.   /* These vars record information from process termination.
  292.      Clear them now before process can possibly terminate,
  293.      to avoid timing error if process terminates soon.  */
  294.   synch_process_death = 0;
  295.   synch_process_retcode = 0;
  296.  
  297.   if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
  298.     strcpy (tempfile = alloca (strlen (outf) + 20), outf);
  299.   else
  300.     {
  301.       tempfile = alloca (20);
  302.       *tempfile = '\0';
  303.     }
  304.   dostounix_filename (tempfile);
  305.   if (*tempfile == '\0' || tempfile[strlen (tempfile) - 1] != '/') 
  306.     strcat (tempfile, "/");
  307.   strcat (tempfile, "detmp.XXX");
  308.   mktemp (tempfile);
  309.  
  310.   outfilefd = creat (tempfile, S_IREAD | S_IWRITE);
  311.   if (outfilefd < 0)
  312.     {
  313.       close (filefd);
  314.       report_file_error ("Opening process output file", Fcons (tempfile, Qnil));
  315.     }
  316. #endif
  317.  
  318.   if (XTYPE (buffer) == Lisp_Int)
  319.     fd[1] = open (NULL_DEVICE, O_WRONLY), fd[0] = -1;
  320.   else
  321.     {
  322. #ifndef MSDOS
  323.       pipe (fd);
  324. #endif
  325. #if 0
  326.       /* Replaced by close_process_descs */
  327.       set_exclusive_use (fd[0]);
  328. #endif
  329.     }
  330.  
  331. #ifdef AMIGA
  332.   {
  333.     register unsigned char *temp;
  334.  
  335.     if (XTYPE (current_buffer->directory) == Lisp_String)
  336.       {
  337.     register int i;
  338.  
  339.     i = XSTRING (current_buffer->directory)->size;
  340.     temp = (unsigned char *) alloca (i + 1);
  341.     bcopy (XSTRING (current_buffer->directory)->data, temp, i);
  342.     temp[i] = 0;
  343.       }
  344.     pid = exec(new_argv[0], new_argv, filefd, fd[1], temp, amiga_process_stack_size);
  345.   }
  346. #else  
  347.   {
  348.     /* child_setup must clobber environ in systems with true vfork.
  349.        Protect it from permanent change.  */
  350.     register char **save_environ = environ;
  351.     register int fd1 = fd[1];
  352.  
  353. #if 0  /* Some systems don't have sigblock.  */
  354.     mask = sigblock (sigmask (SIGCHLD));
  355. #endif
  356.  
  357.     /* Record that we're about to create a synchronous process.  */
  358.     synch_process_alive = 1;
  359.  
  360.     /* These vars record information from process termination.
  361.        Clear them now before process can possibly terminate,
  362.        to avoid timing error if process terminates soon.  */
  363.     synch_process_death = 0;
  364.     synch_process_retcode = 0;
  365.  
  366. #ifdef MSDOS /* MW, July 1993 */
  367.     /* ??? Someone who knows MSDOG needs to check whether this properly
  368.        closes all descriptors that it opens.  */
  369.     pid = run_msdos_command (new_argv, current_dir, filefd, outfilefd);
  370.     close (outfilefd);
  371.     fd1 = -1; /* No harm in closing that one!  */
  372.     fd[0] = open (tempfile, NILP (Vbinary_process_output) ? O_TEXT : O_BINARY);
  373.     if (fd[0] < 0)
  374.       {
  375.     unlink (tempfile);
  376.     close (filefd);
  377.     report_file_error ("Cannot re-open temporary file", Qnil);
  378.       }
  379. #else /* not MSDOS */
  380.     pid = vfork ();
  381.  
  382.     if (pid == 0)
  383.       {
  384.     if (fd[0] >= 0)
  385.       close (fd[0]);
  386. #ifdef USG
  387.         setpgrp ();
  388. #else
  389.         setpgrp (pid, pid);
  390. #endif /* USG */
  391.     child_setup (filefd, fd1, fd1, new_argv, 0, current_dir);
  392.       }
  393. #endif /* not MSDOS */
  394.  
  395.     environ = save_environ;
  396.  
  397.     /* Close most of our fd's, but not fd[0]
  398.        since we will use that to read input from.  */
  399.     close (filefd);
  400.     if (fd1 >= 0)
  401.       close (fd1);
  402.   }
  403. #endif /* not AMIGA */
  404.  
  405.   if (pid < 0)
  406.     {
  407.       if (fd[0] >= 0)
  408.     close (fd[0]);
  409.       report_file_error ("Doing vfork", Qnil);
  410.     }
  411.  
  412.   if (XTYPE (buffer) == Lisp_Int)
  413.     {
  414.       if (fd[0] >= 0)
  415.     close (fd[0]);
  416. #ifndef subprocesses
  417.       /* If Emacs has been built with asynchronous subprocess support,
  418.      we don't need to do this, I think because it will then have
  419.      the facilities for handling SIGCHLD.  */
  420.       wait_without_blocking ();
  421. #endif /* subprocesses */
  422.       return Qnil;
  423.     }
  424.  
  425.   /* Enable sending signal if user quits below.  */
  426.   call_process_exited = 0;
  427.  
  428. #ifdef MSDOS
  429.   /* MSDOS needs different cleanup information.  */
  430.   record_unwind_protect (call_process_cleanup,
  431.              Fcons (make_number (fd[0]), build_string (tempfile)));
  432. #else
  433.   record_unwind_protect (call_process_cleanup,
  434.              Fcons (make_number (fd[0]), make_number (pid)));
  435. #endif /* not MSDOS */
  436.  
  437.  
  438.   if (XTYPE (buffer) == Lisp_Buffer)
  439.     Fset_buffer (buffer);
  440.  
  441.   immediate_quit = 1;
  442.   QUIT;
  443.  
  444.   {
  445.     register int nread;
  446.     int first = 1;
  447.  
  448.     while ((nread = read (fd[0], buf, sizeof buf)) > 0)
  449.       {
  450.     immediate_quit = 0;
  451.     if (!NILP (buffer))
  452.       insert (buf, nread);
  453.     if (!NILP (display) && INTERACTIVE)
  454.       {
  455.         if (first)
  456.           prepare_menu_bars ();
  457.         first = 0;
  458.         redisplay_preserve_echo_area ();
  459.       }
  460.     immediate_quit = 1;
  461.     QUIT;
  462.       }
  463.   }
  464.  
  465.   /* Wait for it to terminate, unless it already has.  */
  466.   wait_for_termination (pid);
  467.  
  468.   immediate_quit = 0;
  469.  
  470.   set_buffer_internal (old);
  471.  
  472.   /* Don't kill any children that the subprocess may have left behind
  473.      when exiting.  */
  474.   call_process_exited = 1;
  475.  
  476.   unbind_to (count, Qnil);
  477.  
  478.   if (synch_process_death)
  479.     return build_string (synch_process_death);
  480.   return make_number (synch_process_retcode);
  481. }
  482. #endif
  483.  
  484. static Lisp_Object
  485. delete_temp_file (name)
  486.      Lisp_Object name;
  487. {
  488.   unlink (XSTRING (name)->data);
  489. }
  490.  
  491. DEFUN ("call-process-region", Fcall_process_region, Scall_process_region,
  492.   3, MANY, 0,
  493.   "Send text from START to END to a synchronous process running PROGRAM.\n\
  494. Delete the text if fourth arg DELETE is non-nil.\n\
  495. Insert output in BUFFER before point; t means current buffer;\n\
  496.  nil for BUFFER means discard it; 0 means discard and don't wait.\n\
  497. Sixth arg DISPLAY non-nil means redisplay buffer as output is inserted.\n\
  498. Remaining args are passed to PROGRAM at startup as command args.\n\
  499. If BUFFER is nil, returns immediately with value nil.\n\
  500. Otherwise waits for PROGRAM to terminate\n\
  501. and returns a numeric exit status or a signal description string.\n\
  502. If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.")
  503.   (nargs, args)
  504.      int nargs;
  505.      register Lisp_Object *args;
  506. {
  507.   register Lisp_Object filename_string, start, end;
  508. #ifdef MSDOS
  509.   char *tempfile;
  510. #else
  511.   char tempfile[20];
  512. #endif
  513.   int count = specpdl_ptr - specpdl;
  514. #ifdef MSDOS
  515.   char *outf = '\0';
  516.  
  517.   if ((outf = egetenv ("TMP")) || (outf = egetenv ("TEMP")))
  518.     strcpy (tempfile = alloca (strlen (outf) + 20), outf);
  519.   else
  520.     {
  521.       tempfile = alloca (20);
  522.       *tempfile = '\0';
  523.     }
  524.   dostounix_filename (tempfile);
  525.   if (tempfile[strlen (tempfile) - 1] != '/')
  526.     strcat (tempfile, "/");
  527.   strcat (tempfile, "detmp.XXX");
  528. #else /* not MSDOS */
  529.  
  530. #ifdef PATH_TEMP
  531.   strcpy (tempfile, PATH_TEMP);
  532. #else /* not PATH_TEMP */
  533. #ifdef VMS
  534.   strcpy (tempfile, "tmp:emacsXXXXXX.");
  535. #else
  536.   strcpy (tempfile, "/tmp/emacsXXXXXX");
  537. #endif
  538. #endif /* not PATH_TEMP */
  539. #endif /* not MSDOS */
  540.  
  541.   mktemp (tempfile);
  542.  
  543.   filename_string = build_string (tempfile);
  544.   start = args[0];
  545.   end = args[1];
  546. #ifdef MSDOS
  547.   specbind (Qbuffer_file_type, Vbinary_process_input);
  548.   Fwrite_region (start, end, filename_string, Qnil, Qlambda);
  549.   unbind_to (count, Qnil);
  550. #else
  551.   Fwrite_region (start, end, filename_string, Qnil, Qlambda);
  552. #endif
  553.  
  554.   record_unwind_protect (delete_temp_file, filename_string);
  555.  
  556.   if (!NILP (args[3]))
  557.     Fdelete_region (start, end);
  558.  
  559.   args[3] = filename_string;
  560.  
  561.   return unbind_to (count, Fcall_process (nargs - 2, args + 2));
  562. }
  563.  
  564. #ifndef VMS /* VMS version is in vmsproc.c.  */
  565. #ifndef AMIGA
  566.  
  567. /* This is the last thing run in a newly forked inferior
  568.    either synchronous or asynchronous.
  569.    Copy descriptors IN, OUT and ERR as descriptors 0, 1 and 2.
  570.    Initialize inferior's priority, pgrp, connected dir and environment.
  571.    then exec another program based on new_argv.
  572.  
  573.    This function may change environ for the superior process.
  574.    Therefore, the superior process must save and restore the value
  575.    of environ around the vfork and the call to this function.
  576.  
  577.    ENV is the environment for the subprocess.
  578.  
  579.    SET_PGRP is nonzero if we should put the subprocess into a separate
  580.    process group.  
  581.  
  582.    CURRENT_DIR is an elisp string giving the path of the current
  583.    directory the subprocess should have.  Since we can't really signal
  584.    a decent error from within the child, this should be verified as an
  585.    executable directory by the parent.  */
  586.  
  587. child_setup (in, out, err, new_argv, set_pgrp, current_dir)
  588.      int in, out, err;
  589.      register char **new_argv;
  590.      int set_pgrp;
  591.      Lisp_Object current_dir;
  592. {
  593. #ifdef MSDOS
  594.   /* The MSDOS port of gcc cannot fork, vfork, ... so we must call system
  595.      instead.  */
  596. #else /* not MSDOS */
  597.   char **env;
  598.   char *pwd_var;
  599.  
  600.   int pid = getpid ();
  601.  
  602. #ifdef SET_EMACS_PRIORITY
  603.   {
  604.     extern int emacs_priority;
  605.  
  606.     if (emacs_priority < 0)
  607.       nice (- emacs_priority);
  608.   }
  609. #endif
  610.  
  611. #ifdef subprocesses
  612.   /* Close Emacs's descriptors that this process should not have.  */
  613.   close_process_descs ();
  614. #endif
  615.   close_load_descs ();
  616.  
  617.   /* Note that use of alloca is always safe here.  It's obvious for systems
  618.      that do not have true vfork or that have true (stack) alloca.
  619.      If using vfork and C_ALLOCA it is safe because that changes
  620.      the superior's static variables as if the superior had done alloca
  621.      and will be cleaned up in the usual way.  */
  622.   {
  623.     register char *temp;
  624.     register int i;
  625.  
  626.     i = XSTRING (current_dir)->size;
  627.     pwd_var = (char *) alloca (i + 6);
  628.     temp = pwd_var + 4;
  629.     bcopy ("PWD=", pwd_var, 4);
  630.     bcopy (XSTRING (current_dir)->data, temp, i);
  631.     if (temp[i - 1] != '/') temp[i++] = '/';
  632.     temp[i] = 0;
  633.  
  634.     /* We can't signal an Elisp error here; we're in a vfork.  Since
  635.        the callers check the current directory before forking, this
  636.        should only return an error if the directory's permissions
  637.        are changed between the check and this chdir, but we should
  638.        at least check.  */
  639.     if (chdir (temp) < 0)
  640.       exit (errno);
  641.  
  642.     /* Strip trailing slashes for PWD, but leave "/" and "//" alone.  */
  643.     while (i > 2 && temp[i - 1] == '/')
  644.       temp[--i] = 0;
  645.   }
  646.  
  647.   /* Set `env' to a vector of the strings in Vprocess_environment.  */
  648.   {
  649.     register Lisp_Object tem;
  650.     register char **new_env;
  651.     register int new_length;
  652.  
  653.     new_length = 0;
  654.     for (tem = Vprocess_environment;
  655.      (XTYPE (tem) == Lisp_Cons
  656.       && XTYPE (XCONS (tem)->car) == Lisp_String);
  657.      tem = XCONS (tem)->cdr)
  658.       new_length++;
  659.  
  660.     /* new_length + 2 to include PWD and terminating 0.  */
  661.     env = new_env = (char **) alloca ((new_length + 2) * sizeof (char *));
  662.  
  663.     /* If we have a PWD envvar, pass one down,
  664.        but with corrected value.  */
  665.     if (getenv ("PWD"))
  666.       *new_env++ = pwd_var;
  667.  
  668.     /* Copy the Vprocess_environment strings into new_env.  */
  669.     for (tem = Vprocess_environment;
  670.      (XTYPE (tem) == Lisp_Cons
  671.       && XTYPE (XCONS (tem)->car) == Lisp_String);
  672.      tem = XCONS (tem)->cdr)
  673.       {
  674.     char **ep = env;
  675.     char *string = (char *) XSTRING (XCONS (tem)->car)->data;
  676.     /* See if this string duplicates any string already in the env.
  677.        If so, don't put it in.
  678.        When an env var has multiple definitions,
  679.        we keep the definition that comes first in process-environment.  */
  680.     for (; ep != new_env; ep++)
  681.       {
  682.         char *p = *ep, *q = string;
  683.         while (1)
  684.           {
  685.         if (*q == 0)
  686.           /* The string is malformed; might as well drop it.  */
  687.           goto duplicate;
  688.         if (*q != *p)
  689.           break;
  690.         if (*q == '=')
  691.           goto duplicate;
  692.         p++, q++;
  693.           }
  694.       }
  695.     *new_env++ = string;
  696.       duplicate: ;
  697.       }
  698.     *new_env = 0;
  699.   }
  700.  
  701.   /* Make sure that in, out, and err are not actually already in
  702.      descriptors zero, one, or two; this could happen if Emacs is
  703.      started with its standard in, out, or error closed, as might
  704.      happen under X.  */
  705.   in = relocate_fd (in, 3);
  706.   if (out == err)
  707.     err = out = relocate_fd (out, 3);
  708.   else
  709.     {
  710.       out = relocate_fd (out, 3);
  711.       err = relocate_fd (err, 3);
  712.     }
  713.  
  714.   close (0);
  715.   close (1);
  716.   close (2);
  717.  
  718.   dup2 (in, 0);
  719.   dup2 (out, 1);
  720.   dup2 (err, 2);
  721.   close (in);
  722.   close (out);
  723.   close (err);
  724.  
  725. #ifdef USG
  726. #ifndef SETPGRP_RELEASES_CTTY
  727.   setpgrp ();            /* No arguments but equivalent in this case */
  728. #endif
  729. #else
  730.   setpgrp (pid, pid);
  731. #endif /* USG */
  732.   /* setpgrp_of_tty is incorrect here; it uses input_fd.  */
  733.   EMACS_SET_TTY_PGRP (0, &pid);
  734.  
  735. #ifdef vipc
  736.   something missing here;
  737. #endif /* vipc */
  738.  
  739.   /* execvp does not accept an environment arg so the only way
  740.      to pass this environment is to set environ.  Our caller
  741.      is responsible for restoring the ambient value of environ.  */
  742.   environ = env;
  743.   execvp (new_argv[0], new_argv);
  744.  
  745.   write (1, "Couldn't exec the program ", 26);
  746.   write (1, new_argv[0], strlen (new_argv[0]));
  747.   _exit (1);
  748. #endif /* not MSDOS */
  749. }
  750. #endif /* not AMIGA */
  751.  
  752. #ifndef AMIGA
  753. /* Move the file descriptor FD so that its number is not less than MIN.
  754.    If the file descriptor is moved at all, the original is freed.  */
  755. int
  756. relocate_fd (fd, min)
  757.      int fd, min;
  758. {
  759.   if (fd >= min)
  760.     return fd;
  761.   else
  762.     {
  763.       int new = dup (fd);
  764.       if (new == -1)
  765.     {
  766.       char *message1 = "Error while setting up child: ";
  767.       char *errmessage = strerror (errno);
  768.       char *message2 = "\n";
  769.       write (2, message1, strlen (message1));
  770.       write (2, errmessage, strlen (errmessage));
  771.       write (2, message2, strlen (message2));
  772.       _exit (1);
  773.     }
  774.       /* Note that we hold the original FD open while we recurse,
  775.      to guarantee we'll get a new FD if we need it.  */
  776.       new = relocate_fd (new, min);
  777.       close (fd);
  778.       return new;
  779.     }
  780. }
  781. #endif /* not AMIGA */
  782.  
  783. static int
  784. getenv_internal (var, varlen, value, valuelen)
  785.      char *var;
  786.      int varlen;
  787.      char **value;
  788.      int *valuelen;
  789. {
  790.   Lisp_Object scan;
  791.  
  792.   for (scan = Vprocess_environment; CONSP (scan); scan = XCONS (scan)->cdr)
  793.     {
  794.       Lisp_Object entry;
  795.  
  796.       entry = XCONS (scan)->car;
  797.       if (XTYPE (entry) == Lisp_String
  798.       && XSTRING (entry)->size > varlen
  799.       && XSTRING (entry)->data[varlen] == '='
  800.       && ! bcmp (XSTRING (entry)->data, var, varlen))
  801.     {
  802.       *value    = (char *) XSTRING (entry)->data + (varlen + 1);
  803.       *valuelen = XSTRING (entry)->size - (varlen + 1);
  804.       return 1;
  805.     }
  806.     }
  807.  
  808.   return 0;
  809. }
  810.  
  811. DEFUN ("getenv", Fgetenv, Sgetenv, 1, 1, 0,
  812.   "Return the value of environment variable VAR, as a string.\n\
  813. VAR should be a string.  Value is nil if VAR is undefined in the environment.\n\
  814. This function consults the variable ``process-environment'' for its value.")
  815.   (var)
  816.      Lisp_Object var;
  817. {
  818.   char *value;
  819.   int valuelen;
  820.  
  821.   CHECK_STRING (var, 0);
  822.   if (getenv_internal (XSTRING (var)->data, XSTRING (var)->size,
  823.                &value, &valuelen))
  824.     return make_string (value, valuelen);
  825.   else
  826.     return Qnil;
  827. }
  828.  
  829. /* A version of getenv that consults process_environment, easily
  830.    callable from C.  */
  831. char *
  832. egetenv (var)
  833.      char *var;
  834. {
  835.   char *value;
  836.   int valuelen;
  837.  
  838.   if (getenv_internal (var, strlen (var), &value, &valuelen))
  839.     return value;
  840.   else
  841.     return 0;
  842. }
  843.  
  844. #endif /* not VMS */
  845.  
  846. /* This is run before init_cmdargs.  */
  847.   
  848. init_callproc_1 ()
  849. {
  850.   char *data_dir = egetenv ("EMACSDATA");
  851.   char *doc_dir = egetenv ("EMACSDOC");
  852.  
  853.   Vdata_directory
  854.     = Ffile_name_as_directory (build_string (data_dir ? data_dir 
  855.                          : PATH_DATA));
  856.   Vdoc_directory
  857.     = Ffile_name_as_directory (build_string (doc_dir ? doc_dir
  858.                          : PATH_DOC));
  859.  
  860.   /* Check the EMACSPATH environment variable, defaulting to the
  861.      PATH_EXEC path from paths.h.  */
  862.   Vexec_path = decode_env_path ("EMACSPATH", PATH_EXEC);
  863.   Vexec_directory = Ffile_name_as_directory (Fcar (Vexec_path));
  864. #ifndef AMIGA
  865.   Vexec_path = nconc2 (decode_env_path ("PATH", ""), Vexec_path);
  866. #else
  867.   {
  868.     char *amiga_path(), *apath = amiga_path();
  869.  
  870.     Vexec_path = nconc2 (decode_env_path (0, apath), Vexec_path);
  871.     Vexec_path = nconc2 (decode_env_path (0, PATH_BIN), Vexec_path);
  872.     free(apath);
  873.   }
  874. #endif  
  875. }
  876.  
  877. /* This is run after init_cmdargs, so that Vinvocation_directory is valid.  */
  878.  
  879. init_callproc ()
  880. {
  881.   char *data_dir = egetenv ("EMACSDATA");
  882.     
  883.   register char * sh;
  884.   Lisp_Object tempdir;
  885.  
  886. #ifndef MSDOS
  887.   if (initialized && !NILP (Vinstallation_directory))
  888.     {
  889.       /* Add to the path the lib-src subdir of the installation dir.  */
  890.       Lisp_Object tem;
  891.       tem = Fexpand_file_name (build_string ("lib-src"),
  892.                    Vinstallation_directory);
  893.       if (NILP (Fmember (tem, Vexec_path)))
  894.     {
  895.       Vexec_path = nconc2 (Vexec_path, Fcons (tem, Qnil));
  896.       Vexec_directory = Ffile_name_as_directory (tem);
  897.  
  898.       /* If we use ../lib-src, maybe use ../etc as well.
  899.          Do so if ../etc exists and has our DOC-... file in it.  */
  900.       if (data_dir == 0)
  901.         {
  902.           tem = Fexpand_file_name (build_string ("etc"),
  903.                        Vinstallation_directory);
  904.           Vdoc_directory = Ffile_name_as_directory (tem);
  905.         }
  906.     }
  907.     }
  908.  
  909.   /* Look for the files that should be in etc.  We don't use
  910.      Vinstallation_directory, because these files are never installed
  911.      in /bin near the executable, and they are never in the build
  912.      directory when that's different from the source directory.
  913.  
  914.      Instead, if these files are not in the nominal place, we try the
  915.      source directory.  */
  916.   if (data_dir == 0)
  917.     {
  918.       Lisp_Object tem, tem1, newdir;
  919.  
  920.       tem = Fexpand_file_name (build_string ("GNU"), Vdata_directory);
  921.       tem1 = Ffile_exists_p (tem);
  922.       if (NILP (tem1))
  923.     {
  924. #ifdef RELPATH_ETC        
  925.       newdir = Fexpand_file_name (build_string (RELPATH_ETC),
  926.                       build_string (PATH_DUMPLOADSEARCH));
  927. #else
  928.       newdir = Fexpand_file_name (build_string ("../etc/"),
  929.                       build_string (PATH_DUMPLOADSEARCH));
  930. #endif
  931.       tem = Fexpand_file_name (build_string ("GNU"), newdir);
  932.       tem1 = Ffile_exists_p (tem);
  933.       if (!NILP (tem1))
  934.         Vdata_directory = newdir;
  935.     }
  936.     }
  937. #endif
  938.  
  939.   tempdir = Fdirectory_file_name (Vexec_directory);
  940.   if (access (XSTRING (tempdir)->data, 0) < 0)
  941.     {
  942.       fprintf (stderr,
  943.            "Warning: arch-dependent data dir (%s) does not exist.\n",
  944.            XSTRING (Vexec_directory)->data);
  945.       sleep (2);
  946.     }
  947.  
  948.   tempdir = Fdirectory_file_name (Vdata_directory);
  949.   if (access (XSTRING (tempdir)->data, 0) < 0)
  950.     {
  951.       fprintf (stderr,
  952.            "Warning: arch-independent data dir (%s) does not exist.\n",
  953.            XSTRING (Vdata_directory)->data);
  954.       sleep (2);
  955.     }
  956.  
  957. #ifdef VMS
  958.   Vshell_file_name = build_string ("*dcl*");
  959. #else
  960.   sh = (char *) getenv ("SHELL");
  961.   Vshell_file_name = build_string (sh ? sh : NAME_SHELL);
  962. #endif
  963. }
  964.  
  965. set_process_environment ()
  966. {
  967.   register char **envp;
  968.  
  969.   Vprocess_environment = Qnil;
  970. #ifndef CANNOT_DUMP
  971.   if (initialized)
  972. #endif
  973.     for (envp = environ; *envp; envp++)
  974.       Vprocess_environment = Fcons (build_string (*envp),
  975.                     Vprocess_environment);
  976. }
  977.  
  978. syms_of_callproc ()
  979. {
  980. #ifdef MSDOS
  981.   Qbuffer_file_type = intern ("buffer-file-type");
  982.   staticpro (&Qbuffer_file_type);
  983.  
  984.   DEFVAR_LISP ("binary-process-input", &Vbinary_process_input,
  985.     "*If non-nil then new subprocesses are assumed to take binary input.");
  986.   Vbinary_process_input = Qnil;
  987.  
  988.   DEFVAR_LISP ("binary-process-output", &Vbinary_process_output,
  989.     "*If non-nil then new subprocesses are assumed to produce binary output.");
  990.   Vbinary_process_output = Qnil;
  991. #endif
  992.  
  993.   DEFVAR_LISP ("shell-file-name", &Vshell_file_name,
  994.     "*File name to load inferior shells from.\n\
  995. Initialized from the SHELL environment variable.");
  996.  
  997.   DEFVAR_LISP ("exec-path", &Vexec_path,
  998.     "*List of directories to search programs to run in subprocesses.\n\
  999. Each element is a string (directory name) or nil (try default directory).");
  1000.  
  1001.   DEFVAR_LISP ("exec-directory", &Vexec_directory,
  1002.     "Directory of architecture-dependent files that come with GNU Emacs,\n\
  1003. especially executable programs intended for Emacs to invoke.");
  1004.  
  1005.   DEFVAR_LISP ("data-directory", &Vdata_directory,
  1006.     "Directory of architecture-independent files that come with GNU Emacs,\n\
  1007. intended for Emacs to use.");
  1008.  
  1009.   DEFVAR_LISP ("doc-directory", &Vdoc_directory,
  1010.     "Directory containing the DOC file that comes with GNU Emacs.\n\
  1011. This is usually the same as data-directory.");
  1012.  
  1013.   DEFVAR_LISP ("configure-info-directory", &Vconfigure_info_directory,
  1014.     "For internal use by the build procedure only.\n\
  1015. This is the name of the directory in which the build procedure installed\n\
  1016. Emacs's info files; the default value for Info-default-directory-list\n\
  1017. includes this.");
  1018.   Vconfigure_info_directory = build_string (PATH_INFO);
  1019.  
  1020.   DEFVAR_LISP ("process-environment", &Vprocess_environment,
  1021.     "List of environment variables for subprocesses to inherit.\n\
  1022. Each element should be a string of the form ENVVARNAME=VALUE.\n\
  1023. The environment which Emacs inherits is placed in this variable\n\
  1024. when Emacs starts.");
  1025.  
  1026. #ifndef VMS
  1027.   defsubr (&Scall_process);
  1028.   defsubr (&Sgetenv);
  1029. #endif
  1030.   defsubr (&Scall_process_region);
  1031. }
  1032.